#pragma strict
////////////////////////////////////////////////////////////////////////////////////
/// 角色移动器.
/// 行为:世界空间(前后左右移动,伴随旋转过度.)
/// 2012.20.24 苏坤
////////////////////////////////////////////////////////////////////////////////////
//移动速度
var moveSpeed:float = 4;
//旋转速度.
var rotFactor:float = 4;
//移动时被阻挡,动画播放速度.
var moveBlockAnimPlaySpeed:float = 0.2;
//正常移动时,动画播放速度.
var moveNormalAnimPlaySpeed:float = 1;
//空闲和移动的动画名称.
var IDLE:String = "noweapon_idle_import";
var MOVE:String = "run_forward_noweapon_import";
//用于测试.
var isTest:boolean;

private var tr:Transform;
private var targetRotation:Quaternion;
private var cc:CharacterController;
var anim:Animation;

function Awake () {
	anim = animation;
	tr = transform;
	cc = GetComponent.<CharacterController>();
	if(! cc)
		cc = gameObject.AddComponent.<CharacterController>();
	
	InitAnimState();
}

function Update () {
	if(isTest){
		var h:float = Input.GetAxis("Horizontal");
		var v:float = Input.GetAxis("Vertical");
		
		PlayAnim(h,v);
	}
}

function StartMoveRot(h:float,v:float){
	Move(h,v);
	Rot(h,v);
	
	SetupAnimSpeed();
	PlayAnim(h,v);	
}

/** 将[-1,1]值转换为(-1,0,1)三个值之一 */
function ToRange(v:float){
	if(v != 0)
		v = v < 0 ? -1 : 1;
	return v;
}
/* 进行移动. */
function Move(h:float,v:float){
	var dir:Vector3 = Vector3(h,0,v);
		dir = Vector3.ClampMagnitude(dir,1);
	if(! cc)
		cc = TransformHelper.GetComponent(gameObject,typeof(CharacterController)) as CharacterController;
	cc.SimpleMove(dir * moveSpeed);
}
/* 进行旋转. */
function Rot(h:float,v:float){
	h = ToRange(h);
	v = ToRange(v);
	var dir:Vector3 = Vector3(h,0,v);
	if(h !=0 || v != 0){
		targetRotation = Quaternion.LookRotation(dir);
	}
	tr.rotation = Quaternion.Slerp(tr.rotation,targetRotation,rotFactor * Time.deltaTime);
}

/* 播放动画. */
function PlayAnim(h:float,v:float){
	var dir:Vector3 = Vector3(h,0,v);
		dir = Vector3.ClampMagnitude(dir,1);
	h = dir.x;
	v = dir.z;
	
	var animName:String = MOVE;
	if(h == 0 && v == 0){
		animName = IDLE;
	}
	if(anim[animName])
		anim.CrossFade(animName);
}

/* 初始好动画 状态 */
function InitAnimState(){
	if(anim[IDLE]){
		anim[IDLE].wrapMode = WrapMode.Loop;
	}
	var state:AnimationState = anim[MOVE];
	if(state){
		state.wrapMode = WrapMode.Loop;
		state.weight = 1;
		state.layer = 0;
	}
}
/* 初始化动画 播放速度 */
function SetupAnimSpeed(){
	var speed:float = moveNormalAnimPlaySpeed;
	if(cc.velocity == Vector3.zero){
		speed = moveBlockAnimPlaySpeed;
	}
	if(anim[MOVE])
		anim[MOVE].speed = speed;
}
